import React from 'react';
import {movieData1} from './data/movieData1.js';
import {movieData2} from './data/movieData2.js';
import {movieData3} from './data/movieData3.js';
import {movieData4} from './data/movieData4.js';
import {movieData5} from './data/movieData5.js';
// import mdata1 from './data/top250_1.json';
// import mdata2 from './data/top250_2.json';
// import mdata3 from './data/top250_3.json';
import {xutil} from './xutil.js';
// import axios from 'axios';
import 'lazysizes';
// import a plugin
// import 'lazysizes/plugins/parent-fit/ls.parent-fit';

// import "lazysizes/plugins/unveilhooks/ls.unveilhooks"; // 背景图片懒加载

const movieData = getMovieData();
const movieDataLen = movieData.length;

for(let i = 0; i< movieDataLen; i++) {
	movieData[i].rank = i + 1;
}

//add simple support for background images:
document.addEventListener('lazybeforeunveil', function(e){
    var bg = e.target.getAttribute('data-bg');
    if(bg){
        e.target.style.backgroundImage = 'url(' + bg + ')';
    }
});


function getMovieData() {
	let movieData = [];

	movieData = xutil.store('movieData');
	if (movieData.length) {
		return movieData;
	}

	// movieData = mdata1.subjects.concat(mdata2.subjects, mdata3.subjects);console.log(movieData);
	movieData = movieData1.subjects.concat(movieData2.subjects, movieData3.subjects, movieData4.subjects, movieData5.subjects);
	console.log(movieData);
	xutil.store('movieData', movieData, 86400 * 7);
	return movieData;
}

function getArrayFields(name, arr) {
	const len = arr.length;
	let res = [];
	for (let i=0; i<len; i++) {
		res.push(arr[i][name]);
	}
	return res;
}

class MovieItem extends React.Component {
	wannaSee(link) {
		console.log('Wanna to See: ' + link);
		window.open(link);
	}

	render() { 	
		const item = this.props.item;
		const backimg = 'https://images.weserv.nl/?url='+(item.images.small ? item.images.small.substring(8) : item.images.large.substring(8));
		// const backimg = 'https://images.weserv.nl/?url='+item.images.small.substring(8);

		let original_title;
		if (item.original_title !== item.title) {
			original_title = (
				<div className="_1mLOP">
					<span>{item.original_title}</span>
				</div>
			);
		}

		const directors = getArrayFields('name', item.directors).join(' ');
		const casts = getArrayFields('name', item.casts).join(' ');

		return (
			<section className="_3N5My">
				<a className="_3sySt">
					<div className="_2GDPl _2jzDr _2mk9o _3a42g" style={{'borderRadius': '4px'}}>
						<div className="d1 movie-img lazyload" data-bg={backimg}>
						</div>
						<div className="_2T26E d2">
						</div>
					</div>
					<div className="khHdl">
						<div className="_3slMf">
							<h1 className="_1B2LW">
								<span>{item.rank}. </span>{item.title}
								<span style={{'color': 'rgb(129, 129, 129)'}}>&nbsp;({item.year})</span>
							</h1>
							<p className="_6LoOw">
								<span className="Si3ne " data-rating="4.5">
									<span className="_32uJy up_Tv undefined"></span>
									<span className="_32uJy up_Tv undefined"></span>
									<span className="_32uJy up_Tv undefined"></span>
									<span className="_32uJy up_Tv undefined"></span>
									<span className="_32uJy _27w7v undefined"></span>
								</span>
								<span className="GFXOX">{item.rating.average}</span>
							</p>
							<div className="_1786N">
								<p className="_1ENqi">
								{item.pubdates ? item.pubdates.join(' ') : item.year} / {item.genres.join(' ')} / {directors} / {casts}
								</p>
							</div>
							<div className="Q2UQj _2l1D7">
								<div className="_3g9NT" onClick={this.wannaSee.bind(this, item.alt)}>
									<div className="_2gKPR">
										<div className="OnzdE">
										</div>
										<div className="_3A9vh">
										想看
										</div>
									</div>
								</div>
							</div>
						</div>
						{original_title}
					</div>
				</a>
			</section>
		)
	}
}

class Search extends React.Component {

	constructor(props) {
		super(props);
		this.onSearchChange = this.onSearchChange.bind(this);
		this.onSearchSubmit = this.onSearchSubmit.bind(this);
	}

	onSearchChange(e) {
		this.props.changeSearch(e.target.value);
	}

	onSearchSubmit(e) {
		e.preventDefault();
	}

	render() {
		const searchText = this.props.searchText;

		return (
			<section className="search-area">
				<form action="/search" id="sb_form" onSubmit={this.onSearchSubmit}>
					<div className="b_searchboxForm" role="search">
						<input className="b_searchbox search-input" name="q" type="search" maxLength="100" value={searchText} onChange={this.onSearchChange} placeholder="搜索..." />
					</div>
				</form>
			</section>
		)
	}
}

class MovieList extends React.Component {
	render() {
		const searchText = this.props.searchText;
		const lists = this.props.lists;	
		const movies = [];
		lists.forEach((item) => {
			let filter = false;
			if (item.title.indexOf(searchText) === -1) filter = true;
			if (filter && (item.year+'').indexOf(searchText) !== -1) filter = false;

			// 根据演员名称筛选
			if (filter) {
				for (let i=0, len=item.casts.length; i<len; i++) {
					if (item.casts[i].name.indexOf(searchText) !== -1) {
						filter = false;
						break;
					}
				}
			}

			// 根据导演名称筛选
			if (filter) {
				for (let i=0, len=item.directors.length; i<len; i++) {
					if (item.directors[i].name.indexOf(searchText) !== -1) {
						filter = false;
						break;
					}
				}
			}
			
			if (filter) return;

			movies.push(<MovieItem key={item.id} item={item} />);
		}); 


		let filterCount;
		if (movies.length < lists.length) {
			filterCount = <p className="filter-count">{movies.length} 条记录</p>
		} else {
			filterCount = '';
		}
		// const movies = lists.map( (item) => {
		// 	console.log(item);
		// 	return 
		// } );

		return (
			<section className="movie-list _3nH2V">
				{filterCount}
				<div className="_1xL9W"><h1 className="_1xhTr">为你推荐</h1></div>
				<div className="_1s9YB">{movies}</div>
			</section>
		)
	}
}

class Movie extends React.Component {
	constructor(props) {
		super(props);

		this.state = {
			searchText: '',
			filterNum: 0
		};

		this.handleSearchChange = this.handleSearchChange.bind(this);
	}

	handleSearchChange(searchText) {
		this.setState({searchText});
	}

	render() {
		return (
			<div id="app">
				<Search searchText={this.state.searchText} changeSearch={this.handleSearchChange} />
				<MovieList searchText={this.state.searchText} lists={movieData} />
			</div>
		);
	}
}

export default Movie;